package com.yunc.modules.oa.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunc.modules.oa.entity.Reimburse;
import com.yunc.modules.oa.mapper.ReimburseMapper;
import com.yunc.modules.oa.service.IReimburseService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户报销表 service实现
 *
 * @author concong tao
 * @since 2019-03-01
 */
@Service
public class ReimburseServiceImpl extends ServiceImpl<ReimburseMapper, Reimburse> implements IReimburseService {

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IdentityService identityService;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean saveReimburse(Reimburse reimburse, Long userId) {
        reimburse.setUserId(userId);
        reimburse.setCreateTime(DateUtil.date());
        boolean flag = this.save(reimburse);
        if (!flag) {
            return flag;
        }
        Map<String,Object> map = new HashMap<>(1);
        map.put("staff", userId);
        map.put("money", reimburse.getMoney());
        // 流程启动
        Long id = reimburse.getId();
        // 先设置流程启动人
        identityService.setAuthenticatedUserId(String.valueOf(userId));
        ExecutionEntity executionEntity = (ExecutionEntity) runtimeService.startProcessInstanceByKey("reimburseProcess", String.valueOf(id), map);
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(executionEntity.getProcessInstanceId()).list();
        if (tasks != null && tasks.size() > 0) {
            Task task = tasks.get(0);
            // 需要下一个处理人
            if (StringUtils.isNotEmpty(reimburse.getAssignee())) {
                taskService.setVariable(task.getId(), "assignee", reimburse.getAssignee());
            }
            taskService.complete(task.getId());
        }
        return true;
    }
}
